package Mydxc.moc;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Xcc
{
	public static void main(String[] args)
	{
		System.out.println("==线程池==");
		
		System.out.println("=线程池测试=");
		/*线程池 ExecutorService(接口)*/
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 0; i < 5; i++)
		{
			
			/**
			 * 参数是Runnable
			 * 传的是 MyRunnable
			 * Future ：未来
			 * 
			 * 多线程执行完后的值是(Call方法的返回值)
			 * 
			 * Future future =es .submit(new MyRunnable());
			 * 
			 * 如果有返回值 那就是null
			 * 如果有返回值 必须等到所有的多线程都运行结束后才能打印
			 */
			Future<String> future=executorService.submit(new MyCallable());
			try
			{
				System.out.println("==main测试=="+future.get());
			}catch(InterruptedException e)
			{
				e.printStackTrace();
			}catch(ExecutionException e)
			{
				e.printStackTrace();
			}
		}
		System.out.println("===============");
		/*重新创建线程池
		 * 根据需要可以指定线程运行的线数*/
		executorService=Executors.newFixedThreadPool(3);
		/*有返回值 main方法等待多线程执行的结果*/
		List<Callable<String>> cs=new ArrayList<Callable<String>>();
		for (int i = 0; i < 5 ; i++)
		{
			/*创建一个Callable*/
			cs.add(new MyCallable());
		}
		/*调用所有多线程*/
		try
		{
			List<Future<String>> futureList =executorService .invokeAll(cs);
			for (Future<String> future : futureList)
			{
				System.out.println("==List循环=="+future.get());
			}
		} catch (InterruptedException e)
		{
	
			e.printStackTrace();
		} catch (ExecutionException e)
		{
		
			e.printStackTrace();
		}
		/*停止线程池*/
		executorService.shutdown();
		System.out.println("=====结束=====");
	}
}
	/**
	 *一个文件夹有很多个类
	 *但只能有一个类被public 修饰
	 *public修饰后的文件名和类名一样 
	 */
class MyRunnable implements Runnable
{

	@Override
	public void run()
	{
		for (int i = 0; i <5; i++)
		{
			try
			{
				Thread.sleep(1000);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"=MyRunnable="+i);
		}
	}
	
}
/**
 *Callable 中的泛型就是方法的返回值 
 */
class MyCallable implements Callable<String>
{

	@Override
	public String call() throws Exception
	{
		for(int i=0 ; i<5 ; i++)
		{
			try
			{
				Thread.sleep(1000);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"MyCallable;"+i);
		}
		return "MyCallable-"+new Date().toLocaleString();
	}
}

